from flask import jsonify
import datetime
import requests


# 统一返回 json 格式
def json(code, message, data):
    return jsonify({'code': code, 'message': message, 'data': data})


def str_split(text):
    output = text.split('：')
    if len(output) == 2:
        return output[1]
    else:
        return ''


# 获取当前时间
def get_current_time():
    current_time = datetime.datetime.now()
    return current_time.strftime("%H:%M")


# 获取当前季节
def get_current_seasons():
    now = datetime.datetime.now()
    month = now.month
    day = now.day

    # 北半球的天文季节开始日期，对应的是南半球的相反
    season_start_dates = {
        '春季': (3, 20),
        '夏季': (6, 21),
        '秋季': (9, 23),
        '冬季': (12, 22)
    }

    for season, (start_month, start_day) in season_start_dates.items():
        if (month, day) >= (start_month, start_day):
            return season

    return '春季'  # 默认值


# 通过IP获取位置
def get_position_by_ip(ip):
    default_position = '江苏 苏州'
    url = 'https://searchplugin.csdn.net/api/v1/ip/get?ip={}'.format(ip)
    resp = requests.get(url)
    if resp.status_code == 200:
        result = resp.json()
        data = result.get('data')
        if data is not None:
            address = data.get('address')
            if address is None:
                address = default_position
            else:
                address = address[:-2]
            return address
        else:
            return default_position
    else:
        return default_position


# 通过生日计算年龄
def get_age_by_birthday(birthday):
    date_object = datetime.datetime.strptime(birthday, '%Y-%m-%d')
    # 获取当前日期
    current_date = datetime.datetime.now()
    # 计算年数差
    years_diff = current_date.year - date_object.year
    # 如果当前日期的月份小于字符串日期的月份，或者月份相同但是日期小于字符串日期的日期，则需要减去一年
    if current_date.month < date_object.month or (
            current_date.month == date_object.month and current_date.day < date_object.day):
        years_diff -= 1
    return years_diff
